<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Enter description here...
 *
 * @package    	Kohadmin
 * @subpackage	Libraries
 * @author     	Thomas Filius
 * @copyright  	(c) 2009 Nobis Stultius IT
 * @license		GNU Lesser General Public License 3
 * @version		$Id $
 */
class KohadminView_Core
{
	private $descriptors = NULL;
	private $descriptors_ignore = array();

	public $defaults = array();
	
	private $dataresources = array();

	private $id = 0;
	private $orm = NULL;

	/**
	 * Constructor. Setup library and initialises settings
	 *
	 */
	public function __construct($modelname = NULL, $id = NULL)
	{
		$this->orm = ORM::factory($modelname);
		$this->id = $id;
		$this->_getSettings();
	}

	/**
	 * Factory method. Creates and returns a new KohadminView object
	 *
	 * @param string $modelname
	 * @return KohadminView
	 */
	public static function factory($modelname = NULL, $descriptors = NULL)
	{
		return new KohadminView($modelname, $descriptors);
	}

	/**
	 * __toString method. Returns the layout and data of this object
	 *
	 * @return string
	 */
	public function __toString()
	{
		return $this->get();
	}

	/**
	 * _getSettings method. Loads config `kohadminindex`
	 *
	 */
	private function _getSettings()
	{
		$this->defaults = Kohana::config('kohadminview.defaults');
	}

	public function get ()
	{
		$view = new View("kohadmin/kohadminview/view");
		$view->data = $this->parse_data();

		return (string) $view;
	}

	private function parse_data ()
	{
		$data = $this->orm->find($this->id);
		
		$return = array();
		foreach ($this->_descriptors_array() as $descriptor) {
			//die (Kohana::debug($this->descriptors)."".Kohana::debug($this->dataresources));
			if (array_key_exists($descriptor, $this->dataresources)) {				
				$return[$descriptor] = $this->dataresources[$descriptor][$data->$descriptor];
			} else {
				$return[$descriptor] = $data->$descriptor;
			}
			
		}

		return $return;
	}

	/**
	 * Returns an array with fields that should be used as descriptors
	 */
	private function _descriptors_array ()
	{
		// no manual input of descriptors, get from DB
		if ( ! $this->descriptors) {
			$this->descriptors = array_keys($this->orm->table_columns);
		}
		$t = array();
		//die(Kohana::debug($this->descriptors));
		foreach ($this->descriptors as $descriptor) {
			// manual set of ignore this descriptor?
			if ( in_array($descriptor, $this->descriptors_ignore))
				continue;
			// config set of ignore this descriptor?
			if ( in_array($descriptor, $this->defaults['ignores']))
				continue;

			$t[] = $descriptor;
		}
		return $t;
	}
	
	public function add_dataresources ($field, $data)
	{
		$this->dataresources[$field] = $data;
		
		return $this;
	}
}
